package com.unicloud.nifi.processor;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.processor.*;
import org.apache.nifi.processor.exception.ProcessException;
import org.apache.nifi.processor.util.StandardValidators;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.*;

public class EmailSenderProccessor extends AbstractProcessor {

    private List<PropertyDescriptor> properties;
    private Set<Relationship> relationships;
    private JavaMailSenderImpl mailSender;

    public static final PropertyDescriptor mail = new PropertyDescriptor.Builder()
            .name("email")
            .required(true)
            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
            .build();


    public static final Relationship SUCCESS = new Relationship.Builder()
            .name("SUCCESS")
            .description("Succes relationship")
            .build();


    @Override
    public void init(final ProcessorInitializationContext context ) {
        ArrayList<PropertyDescriptor> properties = new ArrayList<>();
        properties.add(mail);

//        防止多线程ADD
        this.properties = Collections.unmodifiableList(properties);
        Set<Relationship> relationships = new HashSet<>();
        relationships.add(SUCCESS);
//        防止多线程ADD
        this.relationships = Collections.unmodifiableSet(relationships);

        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost("smtp.163.com");
        mailSender.setProtocol("smtp");
        mailSender.setUsername("gaojiax2014@163.com");
        mailSender.setPassword("tomxin37");
        this.mailSender = mailSender;
    }


    @Override
    public void onTrigger(ProcessContext processContext, ProcessSession processSession) throws ProcessException {
        FlowFile flowFile = processSession.get();
        Map<String, String> attributes = flowFile.getAttributes();
        processSession.read(flowFile, in -> {
            try{
                if(in.available() < 1){
                    return;
                }
                String uuidFileName = UUID.randomUUID().toString();
                File file = new File("D:/" + uuidFileName);
                IOUtils.copy(in,FileUtils.openOutputStream(file));
                // 邮件发送
                MimeMessage message = mailSender.createMimeMessage();
                try {
                    MimeMessageHelper helper = new MimeMessageHelper(message, true);
                    helper.setFrom("gaojiax2014@163.com");
                    helper.setTo("1261368673@qq.com");
                    helper.setSubject("from java client");
                    helper.setText("how are u tom!!", true);
                    helper.addAttachment("喜喜.md", file);
                    mailSender.send(message);
                    System.out.println("带附件的邮件已经发送。");
                } catch (Exception e) {
                    System.out.println("发送带附件的邮件时发生异常！");
                    e.printStackTrace();
                }
            }catch(Exception ex){
                ex.printStackTrace();
                getLogger().error("Failed to read json string.");
            }
        });
        processSession.transfer(flowFile, SUCCESS);
    }

    InputStream fetchAttachFileFromEmail(){
        try {
            return new FileInputStream("D:\\hello.txt");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }




    @Override
    public Set<Relationship> getRelationships(){
        return relationships;
    }

    @Override
    public List<PropertyDescriptor> getSupportedPropertyDescriptors(){
        return properties;
    }

}
